#include "aht20.h"

// AHT20 I2C address
const uint8_t AHT20_I2C_ADDR = 0x70;

// 全局变量用于存储温度和湿度
static float g_temperature = 0;
static float g_humidity = 0;

// 发送数据缓冲区
static uint8_t g_sendBuffer[3] = {0xAC, 0x33, 0x00};
// 接收数据缓冲区
static uint8_t g_recivedBuffer[6] = {0};

// 初始化AHT20
void AHT20_Init(I2C_HandleTypeDef *hi2c)
{
    HAL_Delay(40);
    uint8_t recivedBuffer;
    HAL_I2C_Master_Receive(hi2c, AHT20_I2C_ADDR, &recivedBuffer, 1, HAL_MAX_DELAY);
    if ((recivedBuffer & 0x08) == 0)
    {
        uint8_t sendBuffer[3] = {0xBE, 0x08, 0x00};
        HAL_I2C_Master_Transmit(hi2c, AHT20_I2C_ADDR, sendBuffer, 3, HAL_MAX_DELAY);
        HAL_Delay(20);
    }
}

// 启动读取温湿度
void AHT20_StartRead(I2C_HandleTypeDef *hi2c)
{
    HAL_I2C_Master_Transmit_IT(hi2c, AHT20_I2C_ADDR, g_sendBuffer, 3);
    state = 1;
}

// I2C 传输完成回调函数
void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c)
{
    
    state = 2;
    
}

// I2C 接收完成回调函数
void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c)
{
    if ((g_recivedBuffer[0] & 0x80) == 0)
    {
        g_humidity = (((uint32_t)g_recivedBuffer[3] >> 4) + ((uint32_t)g_recivedBuffer[2] << 4) + ((uint32_t)g_recivedBuffer[1] << 12)) * 100.0f / (1 << 20);
        g_temperature = ((uint32_t)g_recivedBuffer[3] & 0x0F) << 16 | (uint32_t)g_recivedBuffer[4] << 8 | (uint32_t)g_recivedBuffer[5];
        g_temperature = (g_temperature * 200.0f / (1 << 20)) - 50;
    }
    else
    {
        g_humidity = 0;
        g_temperature = 0;
    }
    state =3;
    
}

void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c)
{
    HAL_Delay(100);
    HAL_I2C_Master_Receive_IT(hi2c, AHT20_I2C_ADDR, g_recivedBuffer, 6);
}

// 获取温湿度数据
void AHT20_GetData(float *temperature, float *humidity)
{
    *temperature = g_temperature;
    *humidity = g_humidity;
}
void AHT20_Get()
{
    HAL_I2C_Master_Receive_IT(&hi2c1, AHT20_I2C_ADDR, g_recivedBuffer, 6);
}